#define F_CPU 20000000UL  // 20 MHz CPU clock

#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "serial.h"

// Global variables
Serialt serial;
uint8_t charIn; 								//USART incoming character
char str[] = "\nBlink!\r";
int isEnabled = 1;

int ramp = 0;

ISR (TIMER1_COMPA_vect) // Timer 1 is a 16-bit timer
{
	cli(); // Temporarily disable all interrupts
	
	TCNT1L = 0; // Reset timer
	TCNT1H = 0;
	
	//if( ramp>rampvalue || OCR1AL > 0xD3 )
	if( OCR1AL > 0x30 || ramp == 60)
	{
		OCR1AL = OCR1AL-1;
		ramp = 0;
	}
	else if(OCR1AL > 0x05)
	{
		ramp++;
	}

	PINC |= _BV(PC0); // Toggle LED pin
	
	PINC |= _BV(PC5); // High stepper step pin
	//_delay_ms(100);
	//PORTC &= ~_BV(PC5); // Low stepper step pin

	if(isEnabled && (PORTC & _BV(PC1)) )
	{	
		//for(int i=0; str[i]; i++)
		//	serial_write(&serial, str[i]);
	}

	sei(); // Re-enable interrupts
}

void commMonitor(void)
{
	// Deal with incoming serial bytes here
	if (serial_read(&serial,&charIn)) //if there's data read it
	{
		serial_write(&serial, charIn); //echo it back out for now...
		switch (charIn)
		{
			case 'y':
				isEnabled = 1;
				break;
			case 'n':
				isEnabled = 0;
				break;
			default:
				break;
		}

	}

	return;
}


int main(void) 
{
	
	// Initialization

	
	// 	Set up serial port
	serial_init(&serial);
	
	//	Set up IO pins
	DDRC |= _BV(PC0); // set led pin to output direction
	PORTC |= _BV(PC0); // led on, pin high

	DDRC |= _BV(PC4); // set stepper dir pin to output direction
	PORTC &= ~_BV(PC4); // initialize stepper dir pin to off
	DDRC |= _BV(PC5); // set stepper step pin to output direction
	PORTC |= _BV(PC5); // initialize stepper step pin to off
		
	//	Set up timer
	TCCR1A |= _BV(7) | _BV(6); // Output compare mode, CTC mode, prescaler 1024, set flag to 1
	TCCR1B |= _BV(3) | _BV(2) | _BV(0); 
	OCR1AH = 0x00; // Interrupt each time timer1 gets to this value (which ticks at 20.0Mhz / 1024 = 19.5 kHz)
	OCR1AL = 0xC0; // lower half of previous line. 0x2625 is roughly 0.5 second per toggle
	
	TCNT1H = 0; // Set timer top
	TCNT1L = 0; // Set timer bottom
	
	TIMSK1 |= _BV(1); // Enable timer interrupt

	sei(); // Globally enable interrupts
         
    while (1)                       /* loop forever */
    {
		commMonitor();	// Monitor serial port for incoming bytes
    }
	
	
	return 0;
}
